package com.istudy.dao.xyjdao.impl;


import com.istudy.dao.xyjdao.BaseDao;
import com.istudy.dao.xyjdao.UserIntDao;

import java.sql.*;

/**
 * @author xdd
 * @create 2020-08-25 11:25
 */
public class UserImplDao extends BaseDao implements UserIntDao {

    /**
     * 初始化所需的数据库连接
     * @param conn
     */
    public UserImplDao(Connection conn) {
        super(conn);
    }

    /**
     * 根据指定的用户进行相应的扣费
     *
     * @param userId       用户id
     * @param videoConsume 扣费金额
     * @return 是否扣费成功
     */
    @Override
    public int UserDeduction(int userId, int videoConsume) throws SQLException {
        int i = 0;//是否扣费成功（1成功，2失败）
        String sql = "SELECT IF((SELECT `user`.`user_money` FROM `user` WHERE `user_id`=?) > ?,1,0) AS val;";
        ResultSet resultSet = super.executeQuery(sql, userId, videoConsume);
        if(resultSet.next()){
            int val = resultSet.getInt("val");
            if(val==1){
                String deleteSql=" UPDATE `user`\n" +
                        " SET `user_money`=`user_money` - ?\n" +
                        " WHERE `user`.`user_id`=?;";
                int isNOt = super.executeUpdate(deleteSql, videoConsume, userId);
                if(isNOt>0){
                    i=1;
                }
            }
        }
        return i;
    }
}
